package top.xia17.plugins.fast.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import top.xia17.plugins.fast.common.database.jpa.extension.JpaDtoTxServiceImpl;
import top.xia17.plugins.fast.common.exceptions.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.xia17.plugins.fast.user.dao.entity.Menu;
import top.xia17.plugins.fast.user.dao.entity.Role;
import top.xia17.plugins.fast.user.dao.repository.MenuRepository;
import top.xia17.plugins.fast.user.dao.repository.RoleRepository;
import top.xia17.plugins.fast.user.ds.UserDDS;
import top.xia17.plugins.fast.user.model.dto.RoleDto;
import top.xia17.plugins.fast.user.model.mapstruct.RoleMapstruct;
import top.xia17.plugins.fast.user.service.RoleService;

import java.util.HashSet;
import java.util.List;

/**
 * 角色serviceImpl
 *
 * @author xia17
 * @date 2022/1/17
 */
@Service
@RequiredArgsConstructor
@UserDDS
public class RoleServiceImpl extends JpaDtoTxServiceImpl<Role, RoleDto,Long, RoleRepository, RoleMapstruct> implements RoleService {

    private final MenuRepository menuRepository;


    @Override
    public void createBefore(Role entity) {
        // 角色名是否重复
        if (baseRepository.countAllByName(entity.getName()) > 0) {
            throw new BadRequestException("角色名已经存在!");
        }
    }

    @Override
    public void updateBefore(Role entity, Role resource) {
        // 角色名是否重复
        if (!entity.getName().equals(resource.getName()) && baseRepository.countAllByName(entity.getName()) > 0) {
            throw new BadRequestException("角色名已经存在!");
        }
    }

    @Override
    public void updateProperty(Role entity, Role resource) {
        BeanUtil.copyProperties(resource, entity, false);
    }

    @Override
    public List<Long> getRoleHasMenuIds(Integer id) {
        return this.baseRepository.myFindRoleHasMenuIds(id);
    }

    @Override
    public void setRoleHasMenuIds(Long id, List<Long> menuIds) {
        Role role = this.findByIdOrThrow(id);
        List<Menu> menus = menuRepository.findAllById(menuIds);
        if (menus.size() != menuIds.size()){
            throw new BadRequestException("参数异常!");
        }
        role.setMenus(new HashSet<>(menus));
        this.baseRepository.save(role);
    }
}
